<!--
 * @Author: leiming
 * @Date: 2022-09-09 11:41:46
 * @LastEditors: leiming
 * @LastEditTime: 2022-09-22 14:32:51
 * @Description: file content
-->
<!-- eslint-disable vue/no-mutating-props -->
<template>
    <el-drawer :model-value.sync="isPointDrawerShow" :show-close="true" size="880px" :close-on-click-modal="false"
        modal-class="batch-drawer" :before-close="beforeClose" @closed="handleClose" @opened="openCallBack(uploadFromRef)">
        <template #title>
            <h4>{{ handleImportTypeFilter(type) }}</h4>
        </template>
        <template #default>
            <div v-loading="uploadLoading" class="batch-import">
                <el-row>
                    <el-col :span="24">
                        <el-tabs v-model="activeName" size="small" @tab-click="handleChange">
                            <el-tab-pane :label="`${handleImportTypeFilter(type)}文件`" name="uploadFile">
                                <div class="upload-file">
                                    <el-form ref="uploadFromRef" :model="importForm" label-width="16px">
                                        <el-row>
                                            <el-row type="flex" justify="start" align="top">
                                                <span>1.</span>
                                                <span>{{ `${handleImportTypeFilter(type)}模板` }}</span>
                                                <el-col>
                                                    <el-form-item>
                                                        <el-button class="import-button" @click="downLoadTemp">
                                                            下载模板
                                                        </el-button>
                                                    </el-form-item>
                                                </el-col>
                                            </el-row>

                                            <el-row type="flex" justify="start" align="top">
                                                <span>2.</span>
                                                <span>按照模板填写文件，然后上传校验</span>
                                                <el-col>
                                                    <el-form-item>
                                                        <el-upload ref="upload" v-model:file-list="uploadFileList"
                                                            class="upload-demo" drag :http-request="httpRequest"
                                                            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,text/csv"
                                                            action="" :on-remove="onRemove" :on-change="onFileChange">
                                                            <el-icon class="el-icon--upload">
                                                                <upload-filled />
                                                            </el-icon>
                                                            <div class="el-upload__text">
                                                                把文件拖拽至此，或
                                                                <span class="click-upload">点击上传</span>
                                                                <template class="el-upload-span">
                                                                    仅可上传1个文件，支持csv、xls等excel文件
                                                                </template>
                                                            </div>
                                                        </el-upload>
                                                    </el-form-item>
                                                </el-col>
                                            </el-row>
                                        </el-row>
                                    </el-form>
                                </div>
                            </el-tab-pane>
                            <el-tab-pane label="查询校验结果" name="judgeResult" class="judge-result">
                                <xc-table v-loading="uploadLoading" :data="tableData" :columns="columns"
                                    style="width: 100%;" class="upload-result" :height="maxTableHeight">
                                    <template #createTime="{ row }">
                                        <span>{{ row.createTime.substr(0, row.createTime.lastIndexOf(':')) }}</span>
                                    </template>
                                    <template #mediaType="{ row }" width="100px">
                                        <span>{{ mediaTypeFilter(row.mediaType) }}</span>
                                    </template>
                                    <template #checkStatus="{ row }">
                                        <span v-if="+row.checkStatus === 1" type="text" class="status-button">
                                            待校验
                                        </span>
                                        <span v-if="+row.checkStatus === 2" type="text" class="status-button">
                                            校验中
                                        </span>
                                        <div v-if="[3, 5].includes(+row.checkStatus)" type="text" class="status-button">
                                            <div class="success-button">
                                                通过<span>{{ +row.successNum || 0 }}</span>
                                            </div>
                                            <div class="fail-button">
                                                失败<span>{{ +row.failNum || 0 }}</span>
                                            </div>
                                        </div>
                                        <span v-if="+row.checkStatus === 4" type="text" class="status-button fail-button">
                                            上传失败
                                        </span>
                                    </template>
                                    <template #action="{ row }">
                                        <el-button v-if="[1, 2].includes(+row.checkStatus)" type="text"
                                            @click="onRefresh()">刷新</el-button>
                                        <el-button v-if="[3, 5].includes(+row.checkStatus)" type="text"
                                            @click="onDownloadResult(row)">
                                            下载</el-button>
                                        <el-button v-if="isShowConfirmImportBtn(row)" type="text"
                                            @click="onConfirmImport(row)">
                                            确认导入</el-button>
                                    </template>
                                </xc-table>
                                <p class="result-tip">仅保留近30天的导入记录</p>
                            </el-tab-pane>
                        </el-tabs>
                    </el-col>
                </el-row>
            </div>
        </template>
        <template #footer>
            <div style="flex: auto;">
                <el-button @click="onCancel(uploadFromRef)"> 取消 </el-button>
                <el-button v-if="activeName === 'uploadFile'" type="primary" :disabled="!uploadFileList.length"
                    @click="onCheckFile">
                    校验
                </el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref, defineProps, defineEmits, computed, onMounted, watch } from 'vue';
import { useStore } from 'vuex';
import {
    downloadTemplate,
    importDraft,
    loadFiles,
    downloadContractTemplate,
    importContractTemplate,
    contractReloadRecords,
    sureImportContract,
} from '@/api/houseManage';
import { Upload } from '@x-tech/fe-puma-lib-upload';
import { getSuffix, downLoadCommon, getFileName } from '@/utils/common';
import { ElMessage, ElMessageBox } from 'element-plus';
import { mediaTypeFilter, handleImportTypeFilter } from '@/utils/filters';
import XcTable from '@x-tech/fe-pc-components/src/components/XcTableTemplate/index.vue';
import type { UploadInstance, TabsPaneContext } from 'element-plus';



const isShowConfirmImportBtn = (row: any) => {
    if (props.type === 'PREMISES') return false;
    if (row) {
        if (3 === +row.checkStatus && row.successNum && +row.successNum !== 0) {
            return true;
        }
    }
}
// watch(() => props.type, () => {
//     isShowConfirmImportBtn(null);
// })
const emit = defineEmits(['refresh', 'update:isPointDrawerShow']);
const props = defineProps({
    isPointDrawerShow: {
        type: Boolean,
        default: false,
    },
    type: {
        type: String,
        default: '',
    },
});
console.log('props', props);
const store = useStore();
const commonList: any = computed(() => store.state.app.common.CommonList);
const activeName = ref('uploadFile');
const uploadLoading = ref(false);
// const uploadTmlRef = ref('');
const uploadFromRef = ref('');
const limitType = reactive({
    types: ['xls', 'xlsx', 'csv'],
});
const tableData = ref([]);
const fileList = ref('');
const uploadFileList = ref<any>([]);
const importForm = reactive({
    mediaType: '',
    fileObsUrl: '',
    fileName: '',
});

const columns = ref([
    {
        label: '导入时间',
        key: 'createTime',
        render: true,
        prop: {
            width: '200px',
        },
    },
    {
        label: '文件名称',
        key: 'fileName',
        render: true,
        prop: {
            width: '220px',
        },
    },
    { label: '校验结果', key: 'checkStatus', render: true },
    { label: '操作', key: 'action', render: true },
]);
const judgeUpload = async (file: any): Promise<void> => {
    let upl: any = null;
    if (window.XCConfig.VUE_APP_ENV === 'prod') {
        // 这里关于环境的判断，各项目跟据自身情况修改
        upl = Upload.createProdUpload();
    } else if (window.XCConfig.VUE_APP_ENV === 'test') {
        upl = Upload.createTestUpload();
    } else if (window.XCConfig.VUE_APP_ENV === 'pre') {
        upl = Upload.createPreUpload();
    } else {
        upl = Upload.createDevUpload();
    }
    const suffix = getSuffix(file.file.name);

    const types = limitType.types;
    if (!types.includes(suffix)) {
        ElMessage.info('请上传正确的excel格式文件');
        file.file.status = 'fail';
        return Promise.reject();
    }
    uploadLoading.value = true;
    upl.upload(file.file)
        .then((url: any): void => {
            if (url) {
                importForm.fileObsUrl = url;
                importForm.fileName = file.file.name;
            } else {
                ElMessage.error('上传失败');
            }
            uploadLoading.value = false;
        })
        .catch((e: any) => {
            console.log('e', e);
            uploadLoading.value = false;
            ElMessage.error('上传失败');
        });
};

const onFileChange = (file, fileList) => {
    if (file.raw.status === 'fail') {
        uploadFileList.value = [];
    } else if (fileList.length) {
        uploadFileList.value = [file];
    }
};

const httpRequest = async (rawFile: any) => {
    try {
        await judgeUpload(rawFile);

        fileList.value = rawFile.file.name;
    } catch (error) {
        console.log(error);
    }
};

const onRemove = async () => {
    fileList.value = '';
};

const upload = ref<UploadInstance>();

const onCancel = async (formEl: any): Promise<void> => {
    if (!formEl) {
        return;
    }
    formEl.resetFields();
    beforeClose();
};

const openCallBack = async (formEl: any): Promise<void> => {
    if (!formEl) {
        return;
    }
    formEl.resetFields();
};

const importMediaFun = async (): Promise<void> => {
    const params = {
        fileObsUrl: importForm.fileObsUrl,
        fileName: importForm.fileName,
    };
    try {
        if (props.type === 'SING') {
            await importContractTemplate(params);
        } else {
            await importDraft(params);
        }
    } catch (error) {
        console.log(error);
    }
};

const downLoadTemp = async (): Promise<void> => {
    let res = '';
    uploadLoading.value = true;
    try {
        if (props.type === 'SING') {
            res = await downloadContractTemplate();
        } else {
            res = await downloadTemplate();
        }

        downLoadCommon(res);
    } catch (error) {
        console.log(error);
    }
    uploadLoading.value = false;
};

const reloadRecordsFun = async (): Promise<void> => {
    // let res = [];
    uploadLoading.value = true;
    if (props.type === 'SING') {
        contractReloadRecords()
            .then((res: any) => {
                tableData.value = res;
            })
            .finally(() => {
                uploadLoading.value = false;
            });
    } else {
        loadFiles()
            .then((res: any) => {
                tableData.value = res;
            })
            .finally(() => {
                uploadLoading.value = false;
            });
    }
};

const onCheckFile = async (): Promise<void> => {
    activeName.value = 'judgeResult';
    await importMediaFun();
    await reloadRecordsFun();
};

const handleChange = async (tab: TabsPaneContext, event: Event): Promise<void> => {
    console.log(tab);
    console.log(event);
    if (tab.props.name === 'judgeResult') {
        await reloadRecordsFun();
    }
};

const onRefresh = async (): Promise<void> => {
    await reloadRecordsFun();
    emit('refresh');
};

const onDownloadResult = async (row: any): Promise<void> => {
    if (row.resultUrl) {
        downLoadCommon(row.resultUrl);
    } else {
        ElMessage.error('下载链接为空');
    }
};
const onConfirmImport = async (row: any): Promise<void> => {
    uploadLoading.value = true;
    try {
        await sureImportContract({ fileRecordId: row.fileRecordId });
    } catch (error) {
        console.log(error);
    } finally {
        await reloadRecordsFun();
        // reloadRecordsFun();
    }
    uploadLoading.value = false;
};
// const rowConfig = ref([
//     {
//         color: '#4D88FF',
//         name: '刷新',
//         type: 'refresh',
//         on: (data: any) => {
//             onRefresh();
//         },
//         isPermission: (data: any) => {
//             return [1, 2].includes(+data.row.checkStatus);
//         },
//     },
//     {
//         color: '#4D88FF',
//         name: '下载',
//         type: 'download',
//         on: (data: any) => {
//             onDownloadResult(data.row);
//         },
//         isPermission: (data: any) => {
//             return [3, 5].includes(+data.row.checkStatus);
//         },
//     },
// ]);

// 关闭楼盘图Drawer
const handleClose = () => {
    upload.value!.clearFiles();
    importForm.mediaType = '';
    importForm.fileObsUrl = '';
    importForm.fileName = '';
    uploadFileList.value = [];
    emit('refresh');
};
const beforeClose = () => {
    emit('update:isPointDrawerShow', !props.isPointDrawerShow);
};
const setTableMaxHeightBatch = (): number => {
    let scrollHeight = document.body.scrollHeight;
    let maxHeight = scrollHeight - 270;
    return maxHeight;
};
const maxTableHeight = ref(0);
onMounted(async () => {
    maxTableHeight.value = setTableMaxHeightBatch();
});
</script>

<style lang="scss" scoped>
.batch-import {
    .judge-result {
        .result-tip {
            margin-top: 20px;
            font-size: 14px;
            font-family: PingFang SC-Regular, PingFang SC;
            font-weight: 400;
            color: #bfbfbf;
            line-height: 22px;
            text-align: center;
            margin-bottom: 0;
        }

        .status-button {
            font-size: 14px;
            font-family: PingFang SC-Regular, PingFang SC;
            font-weight: 400;
            color: #ffb414;
            line-height: 22px;
            display: flex;
            flex-direction: column;
        }

        .success-button {
            color: #22ac4e;
        }

        .fail-button {
            color: #e60044;
        }

        .action-right {
            display: flex;
            flex-direction: column;
        }
    }

    .click-upload {
        color: #e60044;
    }

    .download-btn:hover {
        background-color: #fff;
    }

    .download-btn {
        // border-color: #333333;
        // color: #333333;
        // background-color: #fff;
    }

    .upload-result {
        padding: 20px 0 0 0;
    }

    .upload-file {
        margin-top: 24px;
    }
}

::v-deep {
    .el-form {
        .el-form-item {
            margin-bottom: 64px;
            margin-top: 16px;

            .el-form-item__content {
                margin-left: 0 !important;
            }
        }

        .el-step__title {
            font-size: 16px;
        }

        .el-step__title.is-process {
            color: #333333;
            font-weight: 400;
        }

        .el-upload__text {
            font-size: 14px;
            font-weight: 400;
            color: #333333;
            line-height: 16px;

            .el-upload-span {
                display: block;
                font-size: 12px;
                font-weight: 400;
                color: #808080;
                line-height: 14px;
                margin-top: 10px;
            }
        }

        .is-disable-test {
            color: #cccccc;

            .el-upload-span {
                color: #cccccc;
            }
        }
    }

    .el-tabs {
        .el-tabs__header {
            margin-bottom: 0;
        }
    }
}
</style>
